Template.home_prifiles.onCreated(function() {
  this.isEditingName = new ReactiveVar();
  this.isEditingSex  = new ReactiveVar();
  this.isEditingBirth = new ReactiveVar();
  this.isEditingNotes = new ReactiveVar();
});

Template.home_prifiles.helpers({
  isEditingName() {
    return Template.instance().isEditingName.get();
  },
  isEditingSex() {
    return Template.instance().isEditingSex.get();
  },
  isEditingBirth() {
    return Template.instance().isEditingBirth.get();
  },
  isEditingNotes() {
    return Template.instance().isEditingNotes.get();
  },
});

Template.home_prifiles.events({
  // 修改姓名
  'click #editName'(event, instance) {
    instance.isEditingName.set(true);
  },
  'click #cancelEditName'(event, instance) {
    instance.isEditingName.set(false);
  },
  'click #updateName'(event, instance) {
    let nameVal = $.trim($('#profileName').val());

    if (nameVal) {
      Meteor.call('editProfile', 'profile.name', nameVal);
    }

    instance.isEditingName.set(false);
  },
  // 修改性别
  'click #editSex'(event, instance) {
    instance.isEditingSex.set(true);
  },
  'click #cancelEditSex'(event, instance) {
    instance.isEditingSex.set(false);
  },
  'click #updateSex'(event, instance) {
    let sexVal = $('input[name="sexRadio"]:checked').val();

    if (sexVal) {
      Meteor.call('editProfile', 'profile.sex', sexVal);
    }

    instance.isEditingSex.set(false);
  },
  // 修改生日
  'click #editBirth'(event, instance) {
    instance.isEditingBirth.set(true);
  },
  'click #cancelEditBirth'(event, instance) {
    instance.isEditingBirth.set(false);
  },
  'click #updateBirth'(event, instance) {
    let birthVal = $('#profileBirth').val();

    if (birthVal || birthVal != '') {
      Meteor.call('editProfile', 'profile.birth', birthVal);
    }

    instance.isEditingBirth.set(false);
  },
  // 修改个性签名
  'click #editNotes'(event, instance) {
    instance.isEditingNotes.set(true);
  },
  'click #cancelEditNotes'(event, instance) {
    instance.isEditingNotes.set(false);
  },
  'click #updateNotes'(event, instance) {
    let notesVal = $('#profileNotes').val();

    if (notesVal || notesVal != '') {
      Meteor.call('editProfile', 'profile.notes', notesVal);
    }

    instance.isEditingNotes.set(false);
  },
});

Template.prifile_sex_radio.onRendered(function() {
  if (this.data && this.data.sex) {
    if (this.data.sex == '男') {
      $('#maleRadio').attr('checked', 'checked');
    }
    if (this.data.sex == '女') {
      $('#femaleRadio').attr('checked', 'checked');
    }
  }
});

Template.prifile_birth_datepicker.onRendered(function() {
  $('#profileBirth').datepicker({
    autoclose: true,
    language: 'zh-CN'
  });
});